angular.module('mLogin', [])
.service('sLogin', ['localStorageService', '$window', '$http', '$rootScope', '$timeout','rUser', 'rPrivilege',
                    function(localStorage, $window, $http, $rootScope, $timeout, rUser, rPrivilege) {	
	var sResponse = {};
	
	sResponse.firstName = "";
	sResponse.lastName = "";
	sResponse.userName = "";
	sResponse.privilegeIdList = null;
	sResponse.processIdList = null;
	sResponse.isLoggedIn = localStorage.get('token');
	sResponse.userId = null;


	sResponse.logout = function () {
		localStorage.remove('token');
		sResponse.firstName = "";
		sResponse.lastName = "";
		sResponse.userName = "";
		sResponse.privilegeIdList = null;
		sResponse.processIdList = null;
		sResponse.isLoggedIn = null;
		sResponse.userId = null;
		$window.location.href = '/login.html';
	};
	
	sResponse.login = function() {
		if(sResponse.isLoggedIn) {
			
//			var user = new rUser({"id":3,"username":"EXT0289607","createdBy":"EXT0289606","createdDate":null,"firstName":"Evrim","lastName":"Olçum"});
//			user.$save();
//			rUser.query();
//			rUser.get({id:1});
		
			rUser.getLoggedUser().$promise.then(function(result) {
				sResponse.firstName = result.firstName;
				sResponse.lastName = result.lastName;
				sResponse.userName = result.username;
				sResponse.privilegeIdList = null;
				sResponse.processIdList = null;
				sResponse.userId = result.id;
				$rootScope.$broadcast('sLogin');

			});
			rUser.getBusinessProcesses().$promise.then(function(result) {
				sResponse.processList = result;
				$rootScope.$broadcast('sLogin');
				
			});
					
//			user = new rUser({"id":3,"username":"EXT0289608","createdBy":"EXT0289606","createdDate":"2014-09-22","firstName":"Evrim","lastName":"Olçum"});
//			user.$update();
//			user.$delete();
//			rUser.listByUsername({"username": 'EXT0289606'})
		} else {
			sResponse.logout();
		}
		
	}
	return sResponse;
}]);